import {apiUrl} from "~/url";
import StorageUtils from "./storage.utils";

const app = getApp();

class RequestUtils {

    constructor() {
        this._baseUrl = `${apiUrl}`;
        this._requestTask;
        this._requestNum = 0;
    }

     get(url, data) {
        const that = this;
        return new Promise((resolve, reject) => {
            that._request('GET', url, data, (res) => {
                resolve(res);
            })
        })
    }

     post(url, data) {
        const that = this;
        return new Promise((resolve, reject) => {
            that._request('POST', url, data, (res) => {
                resolve(res);
            })
        })
    }

     _request(type, url, data, cb) {
        const that = this;
        that._requestNum++;
        let ifHttp = /^http(s)?:\/\//.test(url);
        if (!ifHttp) {
            url = that._baseUrl + url;
        }
        that._requestTask = wx.request({
             url: url,
             data: {
                 ...data,
                 sysCode: 'JCZN'
             },
             header: {
                 'content-type': 'application/json',
                 'authorization': StorageUtils.getStorageSync('token'),
             },
             dataType: 'json',
             method: type,
             success(res) {
                 const data = res.data;
                 if (data.status === 200) {
                     cb && cb(data.data);
                 } else if (data.status === 201) {
                     console.log('您未登录，请登录后再使用!')
                 } else {
                     console.log('网络异常，请稍后再试！');
                 }
             },
             fail(err) {
                 console.log("网络异常，请稍后再试！");
             },
             complete() {
                 that._requestNum--;
                 if (that._requestNum === 0) {
                     console.log('请求结束');
                 }
             }
        })
    }

     cancelQuest() {
        if (this._requestTask) {
            this._requestTask.abort();
        }
    }
}

export default new RequestUtils();